package com.ys.controller.web.purchase;

import com.ys.config.MenuId;
import com.ys.dto.SubGridConfigDto;
import com.ys.entity.purchase.TcgInvoiceOffset;
import com.ys.entity.purchase.TcgInvoiceOffsetItem;
import com.ys.service.sys.CommonApiService;
import com.ys.vo.W;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 发票管理
 */
@Controller
@RequestMapping("/web/purchase/tcgInvoiceOffsetByManage")
public class WebTcgInvoiceOffsetByManageController {
	private static final Logger logger = LoggerFactory.getLogger(WebTcgInvoiceOffsetByManageController.class);

	@Autowired
	private CommonApiService<TcgInvoiceOffset> commonApiService;

    private final Long MENU_ID = MenuId.TCG_InvoiceOffset_ByManage;


    /*
     * 详情
     */
    @GetMapping("/toDetail")
    public String toDetail(Model model, HttpServletRequest request, HttpServletResponse response,String bid) {
        try {
            Map<String, Object> extraParam = getExtraParam(bid);
            List<Map<String, Object>> itemList = getItemListByBid(bid);
            // 子列表配置信息
            SubGridConfigDto subGridConfig = commonApiService.getSubGrid(MENU_ID,itemList);

            return commonApiService.toDetail(model,Long.parseLong(extraParam.get("id").toString()), new TcgInvoiceOffset(), MENU_ID, extraParam, subGridConfig);
        }catch (Exception e) {
            logger.error("详情页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }


    public Map<String,Object> getExtraParam(String bid){
        Map<String,Object> extraParam = new TcgInvoiceOffset()

                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间

                .addLeftJoin("TB_CompanyInfo C ON C.Vid = A.CompanyVid ")//公司信息表
                .addField("C.Vname AS vname")//购买方公司名称
                .addField("C.Tax AS tax")//购买方公司税号

                .addLeftJoin("TCW_PartnerBankInfo PBI ON PBI.Id = A.PartnerBankInfoId ")//合作商银行账户管理
                .addField("PBI.PartnerName AS partnerName")//供应方公司名称
                .addField("PBI.Vgssh AS vgssh")//供应方公司税号

                .addLeftJoin("TCG_InvoiceRegist IR ON IR.InvoiceOffsetId = A.Id AND IR.EffectStock = 1")//发票登记单
                .addField("IR.InvoiceNo AS invoiceNo")//发票号码
                .addField("IR.InvoiceDay AS invoiceDay")//开票日期
                .addField("IR.AmountNoTax AS amountNoTax")//不含税金额
                .addField("IR.Tax AS invoiceTax")//税额
                .addField("IR.AmountWithTax AS amountWithTax")//含税金额
                .addField("IR.TaxPercent AS taxPercent")//统一税点
                .addField("IR.AnnexFile AS annexFile")//发票附件

                .setBid(bid)
                .queryFirstMap();

        return extraParam;
    }


    //获取子表信息
    public List<Map<String, Object>> getItemListByBid(String bid){

        List<Map<String, Object>> itemList = new TcgInvoiceOffsetItem()


                .addLeftJoin("TCG_PurchaseContractItem PCI ON PCI.Id = A.PurchaseContractItemId ")//采购合同管理子表
                .addField("PCI.Pbid AS purchaseContractBid")//采购合同单号
                .addField("PCI.SubBomNumber AS subBomNumber")//子件BOM数量
                .addField("PCI.SubPurchaseNum AS subPurchaseNum")//子件采购数量
                .addField("PCI.SubPurchasePrice AS subPurchasePrice")//子件采购单价、子件单价（含税）
                .addField("PCI.SubWriteOffNum AS subWriteOffNum")//子件已核销数量

                .addLeftJoin("TCG_PurchaseAppointOrderProductComponent PAC ON PAC.Id = PCI.OrderProductComponentId")//预约采购管理子件表
                .addLeftJoin("TCG_PurchaseAppointOrderItem PAOI ON PAOI.Id = PAC.Pid")//预约采购管理母件表
                .addLeftJoin("TCG_PurchaseAppointOrder PPC ON PPC.Bid = PAOI.Pbid")//预约采购单母表
                .addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = PPC.Vgsbm")//运营公司管理表

                .addField("PPC.Bid AS appointOrderBid")//预约采购单单号
                .addField("PPC.Vgsbm AS vgsbm")//运营公司编码
                .addField("OCA.Vgsjc AS vgsjc")//运营公司简称
                .addField("PAOI.ProductCode AS productCode")//商品编码
                .addField("PAOI.ProductName AS productName")//商品名称
                .addField("PAOI.CodeMerge AS codeMerge")//合并商品编码
                .addField("PAC.SubCode AS subCode")//子件编码
                .addField("PAC.SubName AS subName")//子件名称
                .addField("PAC.SubCodeMerge AS subCodeMerge")//子件合并编码

                .addLeftJoin("TCG_InvoiceRegistItem IRI ON IRI.InvoiceOffsetItemId = A.Id AND IRI.Status = 1 ")//发票登记单子表
                .addField("IRI.SubSinglePriceNoTax AS subSinglePriceNoTax")//子件单价（不含税）
                .addField("IRI.SubTotalPriceNoTax AS subTotalPriceNoTax")//子件总额（不含税）
                .addField("A.OffsetAmount - IRI.SubTotalPriceNoTax AS subTotalPrice")//子件总税额 = 子件总额（含税）- 子件总额（不含税）


                .setPbid(bid)
                .queryMap();

        return itemList;

    }


}






